﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevEx.Thanh.Class;
using DevExpress.XtraGrid.Views.Grid;

namespace DevEx.Thanh.UserControl
{
    public partial class ucUser : DevExpress.XtraEditors.XtraUserControl
    {
        private CRoleController ctrlRole = new CRoleController();
        private CUserController ctrlUser = new CUserController();
        private int _idRole = -1;
        private int _idUser = -1;
        private bool _doiMatKhau = false;
        private tblUser _currentUser = null;
        public ucUser()
        {
            InitializeComponent();
        }

        private void ucUser_Load(object sender, EventArgs e)
        {
            //khởi tạo command
            ucCommands.setControls(groupThongTin.Controls );
            ucCommands.btAdd_ClickEvent = new EventHandler(btAdd_Click);
            ucCommands.btDel_ClickEvent = new EventHandler(btDel_Click);
            ucCommands.btEdit_ClickEvent = new EventHandler(btEdit_Click);
            ucCommands.btHuy_ClickEvent = new EventHandler(btCancel_Click);
            ucCommands.btSave_ClickEvent = new EventHandler(btSave_Click);
            ucCommands.EnableButton(true);
            ucCommands.EnableControl(false, groupThongTin.Controls);
            //bind du lieu vao combobox
            CViewer.BindKhoToLookupEdit(lkKho);
            // bind to list box
            BindToListBox();

        }
        private void btAdd_Click(object sender, EventArgs e)
        {
            btDoiPassword.Enabled = false;
            _idRole = -1;
            if ((lxRoles.SelectedItems.Count > 0))
            {
                _idRole = Convert.ToInt32(lxRoles.SelectedValue );
            }
            //Init obj
            _idUser = -1;
            _currentUser = new tblUser();
            txtUserName.Focus();
        }
        private void btDel_Click(object sender, EventArgs e)
        {
            if (_currentUser !=null)
            {
                if (MessageBox.Show( "Bạn có chắc muốn xóa người dùng: " + _currentUser.UserName +"?","Xác nhận",MessageBoxButtons.YesNo)==DialogResult.Yes)
                {
                    ctrlUser.DeleteRecord3(_currentUser);
                    HienThiGridUser();
                }
            }
        }
        private void btEdit_Click(object sender, EventArgs e)
        {
            btDoiPassword.Enabled = false;
            txtUserName.Enabled = false;
            txtPassword.Enabled = false;
            txtPassword2.Enabled = false;
            txtFullname.Focus();
        }
        private void btCancel_Click (object sender, EventArgs e)
        {
            try
            {
                _idUser = (int)gridView1.GetFocusedRowCellValue("ID_User");
                _currentUser = ctrlUser.SelectRecordByID(_idUser);
                BindDataToTextBox();
            }
            catch (Exception)
            {
                //throw;
            }
            

        }
        private void BindDataToTextBox()
        {
            AnThongBaoLoi();
            if ((_currentUser != null))
            {
                //hien thi ra cac textbox
                txtFullname.Text = _currentUser.FullName;
                txtUserName.Text = _currentUser.UserName;
                txtPassword.Text = "Password";
                txtPassword2.Text = "Password";
                lkKho.EditValue = _currentUser.ID_Kho;
                txtPassword.Enabled = false;
                txtPassword2.Enabled = false;
                btDoiPassword.Enabled = true;
            }
            else
            {
                ucCommands.ResetControl( groupThongTin.Controls );
                lkKho.SelectionStart = -1;
            }

        }
        private Boolean CapNhatNguoiDung()
        {
            AnThongBaoLoi();
            if ((string.IsNullOrEmpty(txtUserName.Text)))
            {
                lblUsernameError.Visible = true;
                txtUserName.Focus();
                return false;
            }
            //check user name co ton tai hay chua
            if ((_idUser == -1))
            {
                if ((ctrlUser.CheckUserExists(txtUserName.Text)))
                {
                    MessageBox.Show("Tên đăng nhập này đã tồn tại! Chọn tên đăng nhập khác!");
                    txtUserName.Text = "";
                    txtUserName.Focus();
                    return false;
                }
            }
            //kiem tra xem cac thong tin da nhap du chua        
            if ((string.IsNullOrEmpty(txtFullname.Text)))
            {
                lblFullnameError.Visible = true;
                txtFullname.Focus();
                return false;
            }
            //check Pass 1 va Pass 2
            if ((_idUser == -1 | _doiMatKhau == true))
            {
                if ((string.IsNullOrEmpty(txtPassword.Text)))
                {
                    lblPass1Error.Visible = true;
                    txtPassword.Focus();
                    return false;
                }
                if ((string.IsNullOrEmpty(txtPassword2.Text)))
                {
                    lblPass2Error.Visible = true;
                    txtPassword2.Focus();
                    return false;
                }
                if ((txtPassword.Text != txtPassword2.Text))
                {
                    txtPassword.Text = "";
                    txtPassword2.Text = "";
                    lblPass2Error.Visible = true;
                    lblPass1Error.Visible = true;
                    txtPassword.Focus();
                    return false;
                }
            }

            _currentUser.UserName = txtUserName.Text;
            _currentUser.FullName = txtFullname.Text;
            if (lkKho.EditValue !=null)
                _currentUser.ID_Kho = (int)lkKho.EditValue; 
            if ((_idUser == -1 | _doiMatKhau == true))
            {_currentUser.Password = CThanh_Utilities.getMd5Hash(txtPassword.Text);
            }
            else
            {
                _currentUser.Password = _currentUser.Password;
            }
            _currentUser.ID_Role = _idRole;
            if ((_idUser != -1))
            {
                ctrlUser .UpdateRecordWithoutAttach(_currentUser);
            }
            else
            {
                ctrlUser .InsertRecord(_currentUser);
            }
            ucCommands.EnableButton(true);
            ucCommands.EnableControl(false, groupThongTin.Controls);
            HienThiGridUser();
            return true;
        }
        private void btSave_Click(object sender, EventArgs e)
        {
            CapNhatNguoiDung();
        }
        private void BindToListBox()
        {
            IQueryable<tblRole> listRoles = ctrlRole.SelectAllRecord();
            lxRoles.DisplayMember = "RoleName";
            lxRoles.ValueMember = "ID_Role";
            lxRoles.DataSource = listRoles;

        }
        private void HienThiGridUser()
        {
            ucCommands.ResetControl(groupThongTin.Controls);
            ucCommands.EnableButton(true);
            ucCommands.EnableControl(false, groupThongTin.Controls);
            //lay danh sach nguoi su dung theo nhom quyen
            //lay danh sach nguoi su dung theo nhom quyen
            _idRole = Convert.ToInt32(lxRoles.SelectedValue);
            //thông tin role
            tblRole role = ctrlRole.SelectRecordByID(_idRole);
            groupUsers.Text = "Danh sách người dùng thuộc nhóm " + role.RoleName;
            //lay ma nhom nguoi dung
            IQueryable listUser = ctrlUser.SelectAllUserByRole2(_idRole);
            gridUser.DataSource = listUser;
            //bind thông tin dòng đầu tiên nếu có dữ liệu
            if (gridView1.RowCount >0)
            {
                _idUser = (int)gridView1.GetFocusedRowCellValue("ID_User");
                _currentUser = ctrlUser.SelectRecordByID(_idUser);
                BindDataToTextBox();
            }
        }
        private void AnThongBaoLoi()
        {
            lblFullnameError.Visible = false;
            lblPass2Error.Visible = false;
            lblPass1Error.Visible = false;
            lblUsernameError.Visible = false;
        }

        private void btDoiPassword_Click(object sender, EventArgs e)
        {
            txtPassword.Enabled = true;
            txtPassword2.Enabled = true;
            _doiMatKhau = true;
            ucCommands.EnableButton(false);
            txtPassword.Focus();
        }

        private void lxRoles_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                HienThiGridUser();
            }
            catch (Exception)
            {
                //throw;
            }
        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                //lấy thông tin user
                _idUser = (int)gridView1.GetFocusedRowCellValue("ID_User");
                _currentUser = ctrlUser.SelectRecordByID(_idUser);
                BindDataToTextBox();
            }
            catch (Exception)
            {
                //throw;
            }
        }

        private void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            GridView view = (GridView)sender;
            //Check whether the indicator cell belongs to a data row
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (Convert.ToInt32(e.RowHandle) + 1).ToString();
                //if (!indicatorIcon)
                e.Info.ImageIndex = -1;
            }
        }
    }
}
